package com.xr.sunnyday.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.StringUtil;
import com.xr.sunnyday.dao.CheckGroupDao;
import com.xr.sunnyday.entity.PageResult;
import com.xr.sunnyday.entity.QueryPageBean;
import com.xr.sunnyday.exception.AssociationException;
import com.xr.sunnyday.pojo.CheckGroup;
import com.xr.sunnyday.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = CheckGroupService.class)
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;

    @Override
    public PageResult findByCondition(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        if(!StringUtil.isEmpty(queryPageBean.getQueryString())){
            queryPageBean.setQueryString("%"+queryPageBean.getQueryString()+"%");
        }
        Page<CheckGroup> page= checkGroupDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    @Transactional
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupDao.add(checkGroup);
        Integer checkGroupId = checkGroup.getId();
        if(null!=checkitemIds){
            for (Integer checkitemId:checkitemIds) {
                //添加检查组与检查项的关系
                checkGroupDao.addCheckGroupCheckItem(checkGroupId, checkitemId);
            }
        }

    }

    @Override
    public List<Integer> findCheckItemIdByCheckGroupId(int checkGroupId) {
        return checkGroupDao.findCheckItemIdByCheckGroupId(checkGroupId);
    }

    @Override
    @Transactional
    public void update(CheckGroup checkGroup, Integer[] checkitemIds) {
        //1.先修改检查组内容
        checkGroupDao.update(checkGroup);
        //2.删除检查组与检查项原有关联
        checkGroupDao.deleteCheckGroupCheckItem(checkGroup.getId());
        //3.重新建立检查组与检查项之间的关联
        if(null!=checkitemIds){
            for (Integer checkitemId:checkitemIds){
                checkGroupDao.addCheckGroupCheckItem(checkGroup.getId(),checkitemId);
            }
        }


    }

    @Override
    public CheckGroup findByCheckGroupId(int checkGroupId) {
        return checkGroupDao.findByCheckGroupId(checkGroupId);
    }

    @Override
    public void deleteById(int id) {
        int count=checkGroupDao.queryCountCheckGroupId(id);
        if(count>0){
            checkGroupDao.deleteCheckGroupCheckItem(id);
        }

        checkGroupDao.deleteById(id);
    }

    @Override
    public List<CheckGroup> queryAll() {
        return checkGroupDao.queryAll();
    }
}
